<template>
  <div v-loading="loading">
    <wang-editor v-model="content" :disabled="isView" style="height: 500px"></wang-editor>

    <div class="my-3">尽调附件</div>

    <div v-if="isView">
      <attach-item v-for="(p, index) of areadyFiles" :attach-data="p" :key="index"></attach-item>
      <!-- <div v-for="file in areadyFiles" :key="file.url" class="file-item">
        <div>{{ file.name }}</div>
        <el-button type="text" @click="handleDownloadFile(file)">下载</el-button>
      </div> -->
      <div v-if="!areadyFiles.length" class="text-muted text-center border p-3">暂无附件</div>
    </div>

    <div v-else>
      <div class="d-flex align-items-stretch">
        <div class="mr-3">
          <input
            type="file"
            ref="uploadInput"
            class="d-none"
            multiple
            accept="*"
            @change="handleFileChange"
          />
          <el-button
            plain
            size="small"
            class="mb-1"
            icon="el-icon-upload2"
            style="height: 100%"
            :disabled="saveLoading"
            @click="handleSelectFile"
          >
            上传
          </el-button>
        </div>
        <div class="flex-1 bg-light p-2 rounded">
          <div v-for="(file, i) in areadyFiles" :key="file.url" class="file-item">
            <attach-item :attach-data="file"></attach-item>
            <el-button type="text" :disabled="saveLoading" @click="handleDeleteFile(1, i)">
              删除
            </el-button>
          </div>
          <div v-for="(file, index) in uploadFiles" :key="index" class="file-item">
            <div>{{ file.name }}</div>
            <el-button type="text" :disabled="saveLoading" @click="handleDeleteFile(2, index)">
              删除
            </el-button>
          </div>
        </div>
      </div>

      <div class="text-center my-3">
        <el-button class="btn-long" type="primary" :loading="saveLoading" @click="handlePass">
          保存
        </el-button>
        <el-button class="btn-long" :loading="saveLoading" @click="handleDismiss">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { uploadOss, deleteOss } from '@/common/api/oss'
import { revokeObjectURL } from '@/common/plugins/tools/file'
import { fileAdapter, attachAdapter } from '@/bank/components/attach/index'
import { exportUrl } from '@/common/api/download'

import WangEditor from '@/components/WangEditor'
import AttachItem from '@/bank/components/attach/Item'
export default {
  components: {
    WangEditor,
    AttachItem,
  },
  props: {
    queryId: String,
    visible: Boolean,
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      related: {},
      loading: false,
      content: '',

      saveLoading: false,
      parentTag: '尽调报告',
      attachTag: '尽调报告',
      areadyFiles: [],
      uploadFiles: [],
      deleteFiles: [],
    }
  },
  computed: {
    isView() {
      return this.viewMode
    },
  },
  watch: {
    visible: {
      handler: function (val) {
        if (val) {
          this.getData()
        }
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    getData() {
      this.reset()
      const { queryId } = this
      if (!queryId) return

      this.loading = true
      return Promise.all([
        this.$api.getData({
          table: 'customer_related',
          params: {
            'customer_related_id.eq': queryId,
          },
        }),
        this.$api.getData({
          table: 'datum_customer_attachment',
          params: {
            'customer_related_id.eq': queryId,
            'attachment_type.eq': this.attachTag,
          },
        }),
      ])
        .then(([res1, res2]) => {
          this.related = res1?.data?.[0] ?? {}
          this.content = this.related.census_report || ''
          this.initForm(res2?.data ?? [])
        })
        .finally(() => {
          this.loading = false
        })
    },

    initForm(val = []) {
      this.areadyFiles = val.reduce((prev, curr) => {
        prev.push(attachAdapter(curr))
        return prev
      }, [])
    },

    reset() {
      this.uploadFiles.forEach(file => {
        revokeObjectURL(file.url)
      })
      this.uploadFiles = []
      this.areadyFiles = []
      this.deleteFiles = []

      this.resetInput()
    },

    resetInput() {
      const { uploadInput } = this.$refs
      if (uploadInput) {
        uploadInput.value = ''
      }
    },

    handleFileChange(e) {
      const { files = [] } = e.target

      for (let i = 0; i < files.length; i++) {
        this.uploadFiles.push(fileAdapter(files[i]))
      }

      this.resetInput()
    },

    handleSelectFile() {
      const { uploadInput } = this.$refs
      uploadInput.click()
    },

    handleDeleteFile(type, index) {
      if (type === 2) {
        const file = this.uploadFiles[index]
        revokeObjectURL(file.url)
        this.uploadFiles.splice(index, 1)
      } else {
        this.deleteFiles.push(...this.areadyFiles.splice(index, 1))
      }
    },

    handlePass() {
      const promises = this.uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/duereport/${this.queryId}`,
          type: 1,
          progress: ({ percent }) => {
            it.percent = percent
            it.loading = percent < 100
          },
        })
      )
      this.saveLoading = true
      return Promise.all(promises)
        .then(list => {
          const attachData = list.map((url, index) => {
            const { viewType, name } = this.uploadFiles[index]
            return {
              attachment: url,
              parent_attachment_type: this.parentTag,
              attachment_type: this.attachTag,
              customer_related_id: this.queryId,
              file_type: viewType === 'image' ? 1 : 2,
              remark: name,
            }
          })
          const updatePromise = [
            this.$api.updateData({
              table: 'customer_related',
              id: this.queryId,
              data: {
                census_report: this.content,
                census_status: 2,
              },
            }),
          ]
          if (attachData.length) {
            updatePromise.push(
              this.$api.addBatch({
                table: 'datum_customer_attachment',
                data: attachData,
              })
            )
          }
          if (this.deleteFiles.length) {
            updatePromise.push(
              this.$api.deleteData({
                table: 'datum_customer_attachment',
                id: this.deleteFiles.map(it => it.id).join(','),
              })
            )
          }
          return Promise.all(updatePromise)
        })
        .then(res => {
          this.$message.success('保存成功！')
          this.$emit('success', res)
          this.deleteOssFiles()
        })
        .catch(() => {
          this.$message.error('保存失败，请重试！')
        })
        .finally(() => {
          this.saveLoading = false
        })
    },

    handleDismiss() {
      this.$emit('dismiss')
    },

    handleDownloadFile(attach) {
      const { attachment: url, name } = attach
      exportUrl({
        url,
        filename: name,
      })
    },

    deleteOssFiles() {
      if (!this.deleteFiles.length) return
      deleteOss(this.deleteFiles.map(it => it.attachment))
    },
  },
}
</script>

<style lang="scss" scoped>
.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px dotted #eee;

  &:last-child {
    border-bottom: none;
  }
}
</style>
